package net.lcheng.shop.Controller;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.lcheng.model.BaseAreas;
import net.lcheng.model.User;
import net.lcheng.model.UserShippingAddress;
import net.lcheng.service.BaseAreasService;
import net.lcheng.service.UserService;
import net.lcheng.service.UserShippingAddressService;
import net.lcheng.shop.vo.CurrentUserModel;
import net.lcheng.vo.UserShippingAddressModel;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.List;
/**
 * Created by zwr on 2016/6/29 0029.
 */
@Controller
public class UserShippingAddressController {
    @Autowired
    private UserShippingAddressService userShippingAddressService;
    @Autowired
    private UserService userService;
    @Autowired
    private BaseAreasService baseAreasService;
    /**
     * 收货地址
     */
    @RequestMapping(value = "address", method = RequestMethod.GET)
    public String addressGet(Model model) {
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()){
            /**获取当前用户*/
            Session session = currentUser.getSession();
            CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            User user = userService.getUserByUserId(currentUserModel.getUserId());
            /**先获取地址*/
            List<UserShippingAddress> addressessList = userShippingAddressService.getUserShippingAddressByUserUserId(user.getUserId());
            model.addAttribute("addressessList", addressessList);
        }else {
            return "redirect:/login";
        }
        return "my/address";
    }
    /**
     * 添加收货地址
     */
    @RequestMapping(value = "add/address", method = RequestMethod.GET)
    public String addAddress(Model model) {
        Subject currentUser = SecurityUtils.getSubject();
        //判断有没有登录
        if (currentUser.isAuthenticated()) {
           // 获取当前用户
            Session session = currentUser.getSession();
            CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            if (!model.containsAttribute("UserShippingAddressModel")) {
                model.addAttribute("UserShippingAddressModel", new UserShippingAddressModel());
                //parentCode获取地区名称
                List<BaseAreas> list = baseAreasService.getParentCodeByAreaName("");
                model.addAttribute("list", list);
            }
        }else{
            return "redirect:/login";
        }
        return "my/add_address";
    }
    /**
     * 添加收货地址post
     */
    @RequestMapping(value = "add/address", method = RequestMethod.POST)
    public String addressPost(Model model, @Valid @ModelAttribute("UserShippingAddressModel") UserShippingAddressModel userShippingAddressModel, BindingResult result) {
        Subject currentUser = SecurityUtils.getSubject();
        //获取当前用户
        Session session = currentUser.getSession();
       CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
        if (result.hasErrors()) {
            return "my/add_address";
        }
        //添加地址的时候判断默认地址有没有选中如果有选中就去掉以前默认的地址）
        if (userShippingAddressModel.getIsDefault()!=null && userShippingAddressModel.getIsDefault() == 1) {
            UserShippingAddress userShippingAddress = userShippingAddressService.getShippingAddressByUserIdAndDefaultType(currentUserModel.getUserId());
            if (userShippingAddress!=null){
                userShippingAddressService.updateIsDefault(userShippingAddress.getAddressId(),0);
            }
        }
        /**获取省名称*/
        BaseAreas provinceCode = baseAreasService.getAreaCodeByAreaName(userShippingAddressModel.getProvinceCode());
        /**获取市名称*/
        BaseAreas cityCode = baseAreasService.getAreaCodeByAreaName(userShippingAddressModel.getCityCode());
        /**获取区名称*/
        BaseAreas districtCode = baseAreasService.getAreaCodeByAreaName(userShippingAddressModel.getDistrictCode());
        String provinceCodeAreaName = (provinceCode.getAreaName());
        String cityCodeAreaName = (cityCode.getAreaName());
        String districtCodeAreaName = (districtCode.getAreaName());
        String userId = (currentUserModel.getUserId());
        String userShippingAddressModelDistrictCode = (userShippingAddressModel.getDistrictCode());
        String userShippingAddressModelProvinceCode = (userShippingAddressModel.getProvinceCode());
        String userShippingAddressModelCityCode = (userShippingAddressModel.getCityCode());
        String userShippingAddressModelConsigneeName = (userShippingAddressModel.getConsigneeName());
        String userShippingAddressModelConsigneePhone = (userShippingAddressModel.getConsigneePhone());
        String userShippingAddressModelAddress = (userShippingAddressModel.getAddress());
        String userShippingAddressModelZipCode = (userShippingAddressModel.getZipCode());
        Integer userShippingAddressModelIsDefault = (userShippingAddressModel.getIsDefault());
        int returnResult = userShippingAddressService.insert(provinceCodeAreaName, cityCodeAreaName, districtCodeAreaName, userId, userShippingAddressModelDistrictCode, userShippingAddressModelProvinceCode, userShippingAddressModelCityCode, userShippingAddressModelConsigneeName, userShippingAddressModelConsigneePhone, userShippingAddressModelAddress, userShippingAddressModelIsDefault,userShippingAddressModelZipCode);
        if (returnResult > 0) {
            model.addAttribute("error", "修改成功");
        } else model.addAttribute("error", "系统异常");

        return "redirect:/address";
    }
    /**
     * 编辑地址
     */
    @RequestMapping(value = "edit/address", method = RequestMethod.GET)
    public String editAddressGet(Model model, @RequestParam String id) {
        if (StringUtils.isEmpty(id)) {
            return "redirect:/user/data";
        }
        //获取当前用户
        Subject currentUser = SecurityUtils.getSubject();
        //判断有没有登录
        if (currentUser.isAuthenticated()) {
            Session session = currentUser.getSession();
           CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            /**获取当前用户地址*/
            UserShippingAddress currentAddress = userShippingAddressService.getAddressByAddressId(id);
            if (currentAddress==null){
                return "redirect:/user/data";
            }
            UserShippingAddressModel userShippingAddressModel=new UserShippingAddressModel();
            userShippingAddressModel.setAddressId(currentAddress.getAddressId());
            userShippingAddressModel.setAddress(currentAddress.getAddress());
            userShippingAddressModel.setZipCode(currentAddress.getZipCode());
            userShippingAddressModel.setConsigneeName(currentAddress.getConsigneeName());
            userShippingAddressModel.setConsigneePhone(currentAddress.getConsigneePhone());
            userShippingAddressModel.setDistrictCode(currentAddress.getDistrictCode());
            model.addAttribute("currentAddress",currentAddress);
            model.addAttribute("UserShippingAddressModel",  userShippingAddressModel);
        }else{
            return "redirect:/login";
        }
        return "my/edit_address";
    }
    /**
     * 编辑地址Post
     */
    @RequestMapping(value = "edit/address", method = RequestMethod.POST)
    public String editAddressPost(Model model, @Valid @ModelAttribute("UserShippingAddressModel") UserShippingAddressModel userShippingAddressModel, BindingResult result) {
        Subject currentUser = SecurityUtils.getSubject();
        //获取当前用户
        Session session = currentUser.getSession();
       CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
        if (result.hasErrors()) {
            UserShippingAddress currentAddress = userShippingAddressService.getAddressByAddressId(userShippingAddressModel.getAddressId());
            model.addAttribute("currentAddress",currentAddress);
            return "my/edit_address";
        }
        //编辑地址的时候判断默认地址有没有选中如果有选中就去掉以前默认的地址）
        if (userShippingAddressModel.getIsDefault()!=null && userShippingAddressModel.getIsDefault() == 1) {
            UserShippingAddress userShippingAddress = userShippingAddressService.getShippingAddressByUserIdAndDefaultType(currentUserModel.getUserId());
            if (userShippingAddress!=null){
                userShippingAddressService.updateIsDefault(userShippingAddress.getAddressId(),0);
            }
        }
        /**获取省名称*/
        BaseAreas provinceCode = baseAreasService.getAreaCodeByAreaName(userShippingAddressModel.getProvinceCode());
        /**获取市名称*/
        BaseAreas cityCode = baseAreasService.getAreaCodeByAreaName(userShippingAddressModel.getCityCode());
        /**获取区名称*/
        BaseAreas districtCode = baseAreasService.getAreaCodeByAreaName(userShippingAddressModel.getDistrictCode());
//        更新地址
        String userShippingAddressModelAddressId = (userShippingAddressModel.getAddressId());
        String provinceCodeAreaName = (provinceCode.getAreaName());
        String cityCodeAreaName = (cityCode.getAreaName());
        String districtCodeAreaName=(districtCode.getAreaName());
        String userShippingAddressModelDistrictCode=(userShippingAddressModel.getDistrictCode());
        String userShippingAddressModelProvinceCode=(userShippingAddressModel.getProvinceCode());
        String  userShippingAddressModelCityCode=( userShippingAddressModel.getCityCode());
        String userShippingAddressModelConsigneeName=(userShippingAddressModel.getConsigneeName());
        String userShippingAddressModelConsigneePhone=(userShippingAddressModel.getConsigneePhone());
        String userShippingAddressModelAddress=( userShippingAddressModel.getAddress());
        Integer  userShippingAddressModelIsDefault=(userShippingAddressModel.getIsDefault());
        String userShippingAddressModelZipCode=(userShippingAddressModel.getZipCode());
        int returnResult = userShippingAddressService.edit(userShippingAddressModelAddressId,provinceCodeAreaName,cityCodeAreaName,districtCodeAreaName,userShippingAddressModelDistrictCode,userShippingAddressModelProvinceCode,userShippingAddressModelCityCode,userShippingAddressModelConsigneeName,userShippingAddressModelConsigneePhone,userShippingAddressModelAddress,userShippingAddressModelIsDefault,userShippingAddressModelZipCode);
        if (returnResult > 0) {
            model.addAttribute("error", "修改成功");
        } else model.addAttribute("error", "系统异常");
        return "redirect:/address";
    }
    /**
     * 删除地址
     */
    @RequestMapping(value = "delete/address", method = RequestMethod.GET)
    public String deleteAddressGet(Model model, @RequestParam String id, RedirectAttributes attributes) {
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            //获取当前用户
            Session session = currentUser.getSession();
           CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            /**获取当前用户地址*/
            UserShippingAddress currentAddress = userShippingAddressService.getAddressByAddressId(id);
            if (currentAddress == null) {
                attributes.addFlashAttribute("error", "参数错误");
                return "redirect:/edit_address";
            }
            //删除
            int returnId = userShippingAddressService.deleteAddress(id);
            if (returnId > 0) {
                attributes.addFlashAttribute("error", "操作成功");
            } else {
                attributes.addFlashAttribute("error", "系统异常");
            }
        }else {
            return "redirect:/login";
        }
        return "redirect:/address";
    }
}